﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Errors;

namespace Ankha.Core
{
    public class Binding
    {
        //Fields
        private object _BindingObj;
        public object BindingObj
        {
            get { return _BindingObj; }
            set
            {
                _BindingObj = value;
                BindingType = typeof(ValueType);
            }
        }

        public Type BindingType { get; set; }
        public string BindingProperty { get; set; }

        //ctor
        public Binding(Type type, string property)
        {
            this.BindingType = type;
            this.BindingProperty = property;
        }

        public Binding(object obj, string property)
        {
            this.BindingObj = obj;
            this.BindingProperty = property;
        }

        //Methods
        public T GetBindingValue<T>()
        {
            PropertyInfo pinfo = null;

            if (BindingObj == null)
            {
                pinfo = BindingType.GetProperty(BindingProperty);
                if (pinfo == null)
                    throw new FrameworkError(Error.InvalidBindingException(this));

                return (T)Convert.ChangeType(pinfo.GetValue(null, null), typeof(T));
            }
            else
            {
                pinfo = BindingObj.GetType().GetProperty(BindingProperty);
                if (pinfo == null)
                    throw new FrameworkError(Error.InvalidBindingException(this));

                return (T)Convert.ChangeType(pinfo.GetValue(BindingObj, null), typeof(T));
            }


        }
        public object GetBindingValue()
        {
            return GetBindingValue<object>();
        }
    }
}
